$(".search-top").css("background",$(".layui-layout-admin .layui-logo", parent.document.body).css("backgroundColor"));
$(".layui-expand-east").css("background",$(".layui-layout-admin .layui-logo", parent.document.body).css("backgroundColor"));
$(".layui-expand-east").css('height',$(window).height());
var $,layer,form,table,laydate,util,laydate,wherestr={},moduleUrl;
layui.use(['table','form','layer','jquery','laydate','element'], function () {
    $ = layui.$,layer = layui.layer,form = layui.form,table = layui.table,laydate=layui.laydate, element = layui.element;
    console.log($('.north').height());
	$.tablelist.init({
		elem: '#dhtable'
		,url: tableUrl
		,where: getWherestr()
		,totalRow: gridColumns.totalRow
   		,cols: [gridColumns.gridBody
		]
		,toolbar: '#toolbar'
		,defaultToolbar: [{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}]
		,height:'full-0'
	});
	//单击选中行
	table.on('row(ftable)', function(obj){
   		obj.tr.find('input[lay-type="layTableRadio"]').prop("checked",true);
       	layui.each(table.cache.dhtable, function(i, item){//重置数据单选属性
      		if(obj.tr.data('index') === i){
               item.LAY_CHECKED = true;
	       	} else {
	           	delete item.LAY_CHECKED;
	       	}
       	});
       	form.render('radio');
   	});
	//双击行事件：查看单据
	table.on('rowDouble(ftable)', function(obj){
		var tabId;
		if(business == 'personneldaxx'){tabId = obj.data.userName}else{tabId = obj.data.bid}
        if(business != 'on' && business != 'personneldajyjl' && business != 'personneldagzjl' && business != 'userbook')parent.layui.index.openTabsPage(openRowUrl+obj.data.nid, businessName+'('+tabId+')');
    });
	//头工具栏事件
	table.on('toolbar(ftable)', function(obj){
		var checkStatus = table.checkStatus('dhtable');
	    switch(obj.event){
	    	case 'addbtn':
				parent.layui.index.openTabsPage(openRowUrl+'0', businessName+' - 新增');
				break;
	    	case 'importBtn':
	  			thStr = '<tr><th><div style="width:30px;">序号</div></th>'
	  			$.each(importFields,function(i,val){
	  				fieldWidth[val] = fieldWidth[val]?fieldWidth[val]:100;			//默认宽度100px
	  				thStr += '<th><div style="width:'+fieldWidth[val]+'px;">' + i + '</div></th>';
	  			})
	  			thStr += '</tr>';
	  			layer.open({
		       		type: 1,
		       		area: ['400px', '230px'],
		       		fix: false,
		       		offset: '10%',
		       		maxmin: true,
		       		shade: 0.3,
		       		title: importTitle,
		       		content: $('#importTpl').html(),
		       		btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
		       		shadeClose: true,
		       		zIndex: 1000,
		       		btn1: function(index, layero){
		       			var file = layero.find('#file');
		       			if(!file[0]['value']){
		       				layer.msg("请选择文件！");
		       				return false;
		       			}
		       			var imRes = importListExcel(file[0], importFields, business);
		       		}
		       	});
	  			break;
	    	case 'exportbtn':
	    		$.ajax({
		   		    url: exportUrl,
		   		    type: 'GET',
		   		    data: getWherestr(),
		   		    dataType: 'json',
		   		    beforeSend: function(){
			   			showloadings(true);
		   		    },
		   		    success: function(result){
		   		    	if (result.code == 0) {
					        window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
						} else if (result.code == web_status.WARNING) {
		                  $.modal.alertWarning(result.msg)
		           		} else {
							$.modal.alertError(result.msg);
						}
				   		showloadings(false);
		   		    }
		   		});
	    		break;
	    	case 'deleteBatch':
	    		if(checkStatus.data.length == 0){
	    			layer.msg("请先选择数据！");
	    		}else{
	    			$.modal.confirmCom('确定要删除么？',function(result){
	    				var infoItems = [];
	    				$.each(checkStatus.data,function(i,v){
	    					if(business == 'personneldaxx'){
	    						infoItems[i] = {nid:v.nid};
	    					}else{
	    						infoItems[i] = {guid:v.guid};
	    					}
	    				})
	    				$.operate.post(delUrl,{infoItems:JSON.stringify(infoItems)},function(result){
	    		       		setTimeout(function(){
	    		       			table.reload('dhtable', {page: {curr: 1},where:getWherestr()});
	    		            }, 1000);
	    		       	});
	    		    });
	    		}
	    		break;
	    	case 'fieldSet':
	    		filedSet(moduleTable);
	    		break;
	    	case 'group':
	    		if(business.split('/')[1]=='group')window.location.href="/business/"+business.split('/')[0];
	    		else window.location.href="/business/"+business+'/listgrouppage';
	    		break;
	    	case 'tail':
	    		if(checkStatus.data.length == 0){
	    			layer.msg("请先选择数据！");
	    		}else{
	    			parent.layui.index.openTabsPage("/business/"+(business.split('/')[1]?business.split('/')[0]:business)+"/tail?bid="+checkStatus.data[0].bid,businessName+'('+checkStatus.data[0].bid+') - 跟踪');
	    		}
	    		break;
	    };
	});
	//监听下拉框——添加条件
	form.on('select(fft)', function(obj){
		fieldAddMore(this);
	});
	//监听排序事件 
	table.on('sort(ftable)', function(obj){
		$.tablelist.sort('dhtable',obj);
	});
	//当前显示的查询字段(包含.search-field)----日期渲染
	$(".search-field").each(function(i,v){
		var fid = $(v).attr("id"), fft = $(v).attr("fft"), ffct = $(v).attr("ffct");
		if(fft == 't_date'){//是日期则需要渲染
			if(ffct == 't_between')laydate.render({elem: '#'+fid,type:'date',trigger:'click',range: '~'});
			else laydate.render({elem: '#'+fid,type:'date',trigger:'click'});
		}
		if(fft == 't_datetime'){//是日期则需要渲染
			if(ffct == 't_between')laydate.render({elem: '#'+fid,type:'datetime',trigger:'click',range: '~'});
			else laydate.render({elem: '#'+fid,type:'datetime',trigger:'click'});
		}
	});
	//搜索按钮
	$('#btn-search').on('click', function () {
	    table.reload('dhtable', {page: {curr: 1},where:getWherestr()});
	});

	//固定查询下拉渲染
	$(".dropdown").each(function(i,v){
		var fieldName = $(v).attr("fieldName");
		var dropdownStr = $('#dropdown_'+fieldName).text()
	 	$(v).append(dropdownStr);
	 	changeDropdown(fieldName);
	 	form.render();
	})
	//添加搜索条件
	function fieldAddMore(obj){
		appendSearch(obj,2);//生成查询条件代码（1：顶部、2：右侧）
		//删除条件
		$(".remove-this").click(function(){
			$(this).parents('.layui-form-item').remove();
			form.render();
		})
	}
	//下拉可编辑
	function changeDropdown(lx){
		form.on('select('+lx+'_select)', function (data) {//选择移交单位 赋值给input框
	        $("#"+lx).val(data.value);
			form.render();////修复下拉框选中后无法消失的问题
	    });
		window.refreshSelect=function(){//失去焦点
	        form.render();//修复下拉框选中后无法消失的问题
		}
	    window.inputSearch = function () {
	    	$("#"+lx).val($("#"+lx).val());
	        var value = $("#"+lx).val();
	        $("#"+lx+"_select").val(value);
	        form.render();
	        $("#"+lx+"_select").next().find("dl").css({ "display": "block" });
	        var dl = $("#"+lx+"_select").next().find("dl").children();
	        var j = -1;
	        for (var i = 0; i < dl.length; i++) {
	            if (dl[i].innerHTML.indexOf(value) <= -1) {
	                dl[i].style.display = "none";
	                j++;
	            }
	            if (j == dl.length-1) {
	                $("#"+lx+"_select").next().find("dl").css({ "display": "none" });
	            }
	        }
	    }
	}
	//获取条件
	function getWherestr(){
		$(".search-field").each(function(i,v){				//当前显示的查询字段(包含.search-field)
			wherestr[v.name]=''
		});
		//动态获取条件的值
		$.each(wherestr,function(i,v){
			if((i.substring(i.length-2,i.length)=='_s' || i.substring(i.length-2,i.length)=='_e') && $("#"+i).attr('fft') != 't_text'){
				if(!$("#"+i.substring(0,i.length-2)).val())wherestr[i]="";
				return;//时间控件的衍生字段需跳出循环
			}
			var vs=$("[name="+i+"]").val();
			switch($("#"+i).attr('fft')){
				case 't_checkcondition':
					if($("#"+i).prop("checked")){
						wherestr[i] = 1;
					}else{
						wherestr[i]='';
					}
				break;
				case 't_radio':
					console.log(i);
					if($("[name='"+i+"']:checked").val()){
						wherestr[i] = $("[name='"+i+"']:checked").val()
					}else{
						wherestr[i]='';
					}
					break;
				case 't_date':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				case 't_datetime':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				default:
					vs?wherestr[i]=vs:wherestr[i]='';
					break;
			}
		});
		return wherestr;
	}
})
//下载导入模板
function getTemplate(){
	$.tablelist.importTemplate(templateUrl);
}
/*批量请求导入数据
 *tobj：导入数据对象
 *startNum：从第几条开始导入
 *oneImportNum：每次导入条数
 *allImportNum：总数据量
 *times：导入次数
 */
var cID = bUser = bDept = stepName = '';
function eachImport(tobj,startNum, oneImportNum, allImportNum, times, timeNum){
	var importObj = [], inum = startNum, importBl='0%', res;
	for(var i = startNum; i < startNum + oneImportNum; i++){
		if(i >= allImportNum)break;
		inum = i + 1 ;
		importObj.push(tobj[i]);
	}
	$.ajaxSettings.async = false;
	$.post(prefix+ "/importpost", {'infoItems':JSON.stringify(importObj, null, 2)}, function(result) {
		importBl = (inum/allImportNum)*100;
		console.log('导入比:'+importBl.toFixed(2)+ '%');
		console.log('数量:'+inum);
		console.log('总次数:'+times);
		console.log('当前次数:'+timeNum);
		importObj = [];
		timeNum += 1;
		res = result;
    },"json");
	setTimeout(function(){
		if(timeNum <= times){
			eachImport(tobj, startNum + oneImportNum, oneImportNum, allImportNum, times, timeNum);	
		}else{
			element.progress('dhprogress', importBl.toFixed(2)+ '%');
			showloadings();
			closeProcess(res);
		}
		element.progress('dhprogress', importBl.toFixed(2)+ '%');
	},500);
}
//隐藏显示侧边
$(".menuBtn i").on('click', function() {
    var btn = $(this);
    if (btn.hasClass('layui-icon-spread-left')) {
        menuHide();
    } else {
        menuShow();
    }
    $(".search-top").animate({ width: 'toggle' }); 
    $(".content-right .layui-form").toggle();
    $(".layui-expand-east").toggle();
})
//显示侧边
function menuShow() {
    $(".content-right").animate({ width: '290px' });
    $(".mid-content").animate({ right: '290px' });
}
//隐藏侧边
function menuHide() {
	$(".content-right").animate({ width: '26px' });
    $(".mid-content").animate({ right: '30px' });
}

